package org.brownflat.watergate.service;

import org.brownflat.watergate.dao.GroupDAO;
import org.brownflat.watergate.dao.UserDAO;
import org.brownflat.watergate.domain.Repository;
import org.brownflat.watergate.domain.User;
import org.brownflat.watergate.domain.UserBuilder;
import org.brownflat.watergate.domain.UserRepository;
import org.brownflat.watergate.domain.UserRepositoryBuilder;
import org.brownflat.watergate.scm.Revision;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
@Service("defaultUserService")
@Transactional
public class DefaultUserService implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private GroupDAO groupDAO;

    @Override
    public User findUserForRevision(Repository repository, Revision revision) {
        Collection<User> allUsers = userDAO.findAll();
        User found = null;

        for(User user : allUsers) {
            List<String> aliases = user.getAliasFor(repository);
            if(aliases.contains(revision.getUser())) {
                found = user;
                break;
            }
        }

        if(found == null) {
            found = createUserFor(repository, revision);
        }

        return found;
    }

    @Override
    public void save(User user) {
        this.userDAO.upsert(user);
    }

    @Override
    /**
     * Will add default group membership to the user before
     * saving.
     */
    public void saveNewUser(User user) {
        user.addGroups(groupDAO.findDefaultGroups());
        save(user);
    }

    private User createUserFor(Repository repository, Revision revision) {
        String aliasAndUserName = revision.getUser();

        UserRepositoryBuilder userRepositoryBuilder = new UserRepositoryBuilder();
        userRepositoryBuilder = userRepositoryBuilder.withRepository(repository);
        userRepositoryBuilder = userRepositoryBuilder.withAlias(aliasAndUserName);

        UserBuilder userBuilder = new UserBuilder();
        userBuilder = userBuilder.withPassword("password");
        userBuilder = userBuilder.withUsername(aliasAndUserName);
        userBuilder = userBuilder.withFullName(aliasAndUserName);

        User user = userBuilder.build();
        userRepositoryBuilder = userRepositoryBuilder.withUser(user);
        UserRepository userRepository = userRepositoryBuilder.build();
        user.addUserRepository(userRepository);

        saveNewUser(user);
        return user;
    }
}
